/*
 * @Author: yangzonglong
 * @Date: 2020-06-15 14:07:19
 * @version: v1.0.0
 * @Descripttion: 
 * @LastEditors: yangzonglong
 * @LastEditTime: 2023-10-07 16:40:02
 * @Auditor: 
 */
import server from './../../utils/server/server';

let _cache: Record<string, {
  nexts: Function[],
  inRequest?: boolean,
  data?: any
}> = {};

export async function waitServer(url: string, params: Record<string, any>, next: Function, cacheKey?: string) {
  if (cacheKey) {
    if (!_cache[cacheKey]) _cache[cacheKey] = { nexts: [] };

    if (_cache[cacheKey].inRequest) {
      if (_cache[cacheKey].data) {
        return next(_cache[cacheKey].data);
      } else return _cache[cacheKey].nexts.push(next);
    }
    _cache[cacheKey].inRequest = true;
    _cache[cacheKey].nexts = [next];
  }
  try {
    const where = params?.where || {};
    let result: any = { rows: [], count: 0 };

    if (where.$or?.length === 0) {
      if (url.includes('findAll')) result = [];
    }else {
      result = await server(url, params);
    }

    if (cacheKey) {
      _cache[cacheKey].nexts.forEach((fn: Function) => fn(result));
      _cache[cacheKey].data = result;
      _cache[cacheKey].nexts = [];
    } else {
      next(result)
    }
  } catch (error) {
    if (cacheKey) {
      _cache[cacheKey].nexts = [];
    } else {
      next([])
    }
  }
}

export async function getData(url: string, query: object, cacheKey?: string, rtnDataAfter?: Function, next?: Function) {
  try {
    waitServer(url, query, (result: { rows: any[] }) => {
      const rows = rtnDataAfter ? rtnDataAfter(result) : (result.rows || result);
      next?.(rows)
    }, cacheKey);

  } catch (error) {
    next?.([])
  }
}